package co.laomag.coffee.utils;

import co.laomag.coffee.model.vo.AdminVo;
import com.alibaba.fastjson.JSON;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 马泽朋
 * @version 1.0
 * @date 2020/4/18 下午 4:08
 */
@Component
public class RedisUtils {
    @Resource
    private  StringRedisTemplate stringRedisTemplate;

    /**
     * 保存token
     * @param adminVo 需要保存token的对象
     */
    public  void saveToken(AdminVo adminVo){
        stringRedisTemplate.opsForValue().set(adminVo.getToken(), JSON.toJSONString(adminVo));
        stringRedisTemplate.opsForValue().set("admin-" + adminVo.getPhone(), adminVo.getToken());
    }

    /**
     * 验证token是否存在
     * @param token
     * @return 存在则为真
     */
    public  Boolean verificationToken(String token){
        try {
            return stringRedisTemplate.hasKey(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取指定key的值
     * @param token key
     * @return 值
     */
    public  String getValue(String token){
        return stringRedisTemplate.opsForValue().get(token);
    }

    /**
     *  获取缓存的用户对象
     * @param token
     * @return 存在则返回对象,不存在返回null
     */
    public  AdminVo getAdmin(String token){
        AdminVo adminVo = null;
        Boolean aBoolean = verificationToken(token);
        if (aBoolean){
            String s = stringRedisTemplate.opsForValue().get(token);
            adminVo = JSON.parseObject(s, AdminVo.class);
        }
        return adminVo;
    }

    /**
     * 删除指定的token
     * @param token redis的KEY
     */
    public  void deleteToken(String token){
        Boolean aBoolean = verificationToken(token);
        if (aBoolean){
            stringRedisTemplate.delete(token);
        }

    }


}
